package database.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;

import model.Address;
import model.Contact;
import database.DBConnection;

public class AddressDAO {

	public static void insertAddressesToDB(LinkedList<Address> addresses, int subjectId, int subjectType){
		DBConnection newConnection = new DBConnection();
		newConnection.connect();
		
		for(Address a: addresses){
			try{
				PreparedStatement stmt = newConnection.getConnection().prepareStatement("INSERT INTO Address(address_type_fk, subject_fk, subject_type_fk, country, county, town_village, street_address, zipcode) "
						+"VALUES (?,"+subjectId+","+subjectType+",?,?,?,?,?)");
				stmt.setInt(1, a.getAddressType());
				stmt.setString(2, a.getCountry());
				stmt.setString(3, a.getCounty());
				stmt.setString(4, a.getTown_village());
				stmt.setString(5, a.getStreet_address());
				stmt.setString(6, a.getZipcode());
				
				
				System.out.println("SQL on: " + stmt);
				stmt.executeUpdate();
				newConnection.closeConnection();
			}catch(SQLException e){
				e.printStackTrace();
			}	
		}
	}
	public static LinkedList<Address> toAddresses(ResultSet resultSet){
		LinkedList<Address> addresses = new LinkedList<Address>();
		
		try {
			while (resultSet.next()) {
				Address address = new Address();
				address.setAddressId(resultSet.getInt("address"));
				address.setAddressType(resultSet.getInt("address_type"));
				address.setCountry(resultSet.getString("country"));
				address.setCounty(resultSet.getString("county"));
				address.setTown_village(resultSet.getString("town_village"));
				address.setStreet_address(resultSet.getString("street_address"));
				address.setZipcode(resultSet.getString("zipcode"));
				addresses.add(address);
			}

		}catch (Exception ex) {
			ex.printStackTrace();
			// MyLogger.Log("Auth.UserAuth():",ex.getMessage());
		}
		return addresses;
	}

}
